<template>
  <div>
    <audio @timeupdate="updateProgress" controls ref="audioRef" style="display: none">
      <source :src="url" type="audio/mpeg" />
      您的浏览器不支持音频播放
    </audio>
    <div :class="btnsIcon ? 'audio_btn' : 'audio_right'">
      <img
        v-if="!audioIsPlay"
        @click="playAudio"
        class="audio_icon"
        src="@/assets/img/pause.png"
        alt="播放"
      />
      <img
        v-if="audioIsPlay"
        @click="playAudio"
        class="audio_icon"
        src="@/assets/img/play.png"
        alt="暂停"
      />
      <el-slider
        :class="btnsIcon ? 'audio_none' : 'slider_box'"
        v-model="currentProgress"
        :show-tooltip="false"
        @input="handleProgressChange"
      />
      <div :class="btnsIcon ? 'audio_none' : 'audio_time'">
        <span class="audio_current">{{ audioStart }}</span>
        &nbsp;/&nbsp;
        <span class="audio_total">{{ durationTime }}</span>
      </div>
      <div :class="btnsIcon ? 'audio_none' : 'volume'">
        <div class="volume_progress" v-show="audioHuds">
          <el-slider
            vertical
            height="100px"
            class="volume_bar"
            v-model="audioVolume"
            :show-tooltip="false"
            @change="handleAudioVolume"
          />
        </div>
        <img
          class="volume_icon"
          v-if="audioVolume <= 0"
          @click.stop="audioHuds = !audioHuds"
          src="@/assets/img/audio_mute.png"
          alt=""
        />
        <img
          class="volume_icon"
          v-if="audioVolume > 0"
          @click.stop="audioHuds = !audioHuds"
          src="@/assets/img/audio_high.png"
          alt=""
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import log from '@/utils/log.ts'
const props = defineProps({
  url: {
    type: String
  }, //试听的链接
  isPauseTtsAudio: {
    type: Boolean,
    default: () => false
  }, //是否暂停播放试听
  btnsIcon: {
    type: Boolean,
    default: () => false //是否只需要一个播放按钮
  }
})
const audioIsPlay = ref(true) //音频是否在播放
const audioStart = ref('0:00')
const durationTime = ref('0:00') //音频的总时长，显示的时间格式
const duration = ref(0) //音频的总时长
const audioVolume = ref(80) //音量的默认值是0.8
const audioHuds = ref(false) //是否显示音量slider
const audioRef = ref(null)
const currentProgress = ref(0)

const emit = defineEmits(['scrollToWhere'])

onMounted(() => {
  countAudioTime()
})
/*获取音频时长*/
const countAudioTime = async () => {
  const audio = new Audio()
  audio.src = props.url
  while (isNaN(audio.duration) || audio.duration === Infinity) {
    // 延迟一会 不然网页都卡死
    await new Promise((resolve) => setTimeout(resolve, 200))
    // 设置随机播放时间，模拟调进度条
    audio.currentTime = 10000000 * Math.random()
  }
  duration.value = audio.duration
  durationTime.value = transTime(audio.duration)
  log.success('音频的总时长:', audio.duration)
}
// 音频播放时间换算
const transTime = (duration) => {
  const minutes = Math.floor(duration / 60)
  const seconds = Math.floor(duration % 60)
  const formattedMinutes = String(minutes).padStart(2, '0') //padStart(2,"0") 使用0填充使字符串长度达到2
  const formattedSeconds = String(seconds).padStart(2, '0')
  return `${formattedMinutes}:${formattedSeconds}`
}
// 播放暂停控制
const playAudio = () => {
  if (audioRef.value.paused) {
    audioRef.value.play()
    audioIsPlay.value = false
  } else {
    audioRef.value.pause()
    audioIsPlay.value = true
  }
}

// 根据当前播放时间，实时更新进度条
const updateProgress = (e) => {
  var value = e.target.currentTime / e.target.duration
  emit('scrollToWhere', Math.floor(value * 100))
  if (audioRef.value?.play) {
    currentProgress.value = value * 100
    audioStart.value = transTime(audioRef.value.currentTime)
  }
}
//调整播放进度
const handleProgressChange = (val) => {
  log.error('手动拖动进度', val)
  if (!val) {
    return
  }
  let currentTime = duration.value * (val / 100)
  // 更新音频的当前播放时间
  audioRef.value.currentTime = currentTime
  emit('scrollToWhere', val)
  // emit('scrollToWhere', currentTime)
}
//调整音量
const handleAudioVolume = (val) => {
  audioRef.value.volume = val / 100
}
//设置进度
const seekTotime = (val) => {
  if (!val) {
    return
  }
  // 更新音频的当前播放时间
  audioRef.value.currentTime = val
}
defineExpose({ seekTotime })
</script>

<style lang="scss" scoped>
.audio_none {
  display: none;
}
.audio_btn {
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #0052cc;
  border-radius: 4px;
  box-sizing: border-box;
  position: relative;
  .slider_box {
    width: 160px;
    height: 4px;
    border-radius: 5px;
    background-color: #f1f1f1;
    flex: 1;
    margin: 0 8px 4px;
  }
  .audio_icon {
    width: 20px;
    height: 20px;
    margin-bottom: 4px;
    cursor: pointer;
  }
  .audio_time {
    color: #f1f1f1;
    overflow: hidden;
    font-size: 12px;
    position: absolute;
    bottom: 3px;
    left: 80px;
    .audio_total {
      float: right;
    }
    .audio_current {
      float: left;
    }
  }
}
.audio_right {
  width: 230px;
  height: 40px;
  display: flex;
  align-items: center;
  background: #0052cc;
  border-radius: 4px;
  padding: 0 10px;
  box-sizing: border-box;
  position: relative;
  .slider_box {
    width: 160px;
    height: 4px;
    border-radius: 5px;
    background-color: #f1f1f1;
    flex: 1;
    margin: 0 8px 4px;
  }
  .audio_icon {
    width: 20px;
    height: 20px;
    margin-bottom: 4px;
    cursor: pointer;
  }
  .audio_time {
    color: #f1f1f1;
    overflow: hidden;
    font-size: 12px;
    position: absolute;
    bottom: 3px;
    left: 80px;
    .audio_total {
      float: right;
    }
    .audio_current {
      float: left;
    }
  }
}
.volume {
  position: relative;
  .volume_progress {
    width: 32px;
    height: 140px;
    position: absolute;
    top: -142px;
    right: -4px;
  }
  .volume_bar {
    background: #fff;
    border-radius: 4px;
  }
  .volume_icon {
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.el-slider__button-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}
.slider_box,
.volume_bar {
  .el-slider__button {
    width: 8px;
    height: 8px;
    border: none;
  }
  .el-slider__bar {
    background: #00db15;
  }
}
.slider_box {
  .el-slider__button-wrapper {
    width: 8px;
  }
}
.volume_bar {
  .el-slider__runway {
    margin: 0 14px !important;
  }
}
</style>
